/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

/**
 *
 * @author percynguyen92
 */
import Model.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
/**
 *
 * @author percynguyen92
 */
public class Login extends javax.swing.JFrame {
    private String realpath;
    public String[] listUser;

    /**
     * Creates new form LoginGUI
     */
    public Login() {
        initComponents();
        //this.setVisible(true);
        this.setLocation(500, 200);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jbtnDangNhap = new javax.swing.JButton();
        jlblMSSV = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jtfMSSV = new javax.swing.JTextField();
        jbtnNapDuLieu = new javax.swing.JButton();
        jpwfMatKhau = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Đăng Nhập");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(51, 51, 255));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Đăng Nhập");
        jLabel1.setToolTipText("");
        jLabel1.setName(""); // NOI18N

        jbtnDangNhap.setText("Đăng nhập");
        jbtnDangNhap.setToolTipText("Đăng nhập");
        jbtnDangNhap.setEnabled(false);
        jbtnDangNhap.setMaximumSize(new java.awt.Dimension(85, 30));
        jbtnDangNhap.setMinimumSize(new java.awt.Dimension(85, 30));
        jbtnDangNhap.setPreferredSize(new java.awt.Dimension(85, 30));
        jbtnDangNhap.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jbtnDangNhapMouseClicked(evt);
            }
        });

        jlblMSSV.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jlblMSSV.setText("Mã số sinh viên :");

        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel3.setText("Mật khẩu :");

        jtfMSSV.setEnabled(false);

        jbtnNapDuLieu.setText("Nạp dữ liệu");
        jbtnNapDuLieu.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jbtnNapDuLieuMouseClicked(evt);
            }
        });

        jpwfMatKhau.setEnabled(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(64, Short.MAX_VALUE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(64, 64, 64))
            .addGroup(layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jtfMSSV)
                        .addComponent(jbtnDangNhap, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jbtnNapDuLieu, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE)
                        .addComponent(jpwfMatKhau))
                    .addComponent(jlblMSSV))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jlblMSSV, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jtfMSSV, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jpwfMatKhau, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jbtnDangNhap, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnNapDuLieu, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(30, 30, 30))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-243)/2, (screenSize.height-325)/2, 243, 325);
    }// </editor-fold>//GEN-END:initComponents

    private void jbtnDangNhapMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbtnDangNhapMouseClicked
        if(checkUser(this.jtfMSSV.toString(), this.jpwfMatKhau.toString()))
        {
            JOptionPane.showMessageDialog(null, "Đăng nhập thành công");
            /*Test test;
            test = new Test();
            test.show();
            this.dispose();*/
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Sai");
        }
        //JOptionPane.showMessageDialog(null, listUser.length-1);
    }//GEN-LAST:event_jbtnDangNhapMouseClicked

    private boolean checkUser(String MSSV, String MatKhau)
    {
        boolean isExist=false;
        for(int i=1; i<listUser.length; i++)
        {
            String[] user = listUser[i].split("/");
            if(user[0].equals(MSSV) && user[0].equals(MatKhau))
            {
                isExist = true;
            }
        }
        return isExist;
    }
    
    private void jbtnNapDuLieuMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbtnNapDuLieuMouseClicked
        //Đọc file listUser và ghi vào mảng
        JFileChooser fileChooser = new JFileChooser();
        javax.swing.filechooser.FileFilter ff = new javax.swing.filechooser.FileFilter() {

            @Override
            public boolean accept(File file) {
                return file.isDirectory() || file.getName().toLowerCase().endsWith(".txt");
            }

            @Override
            public String getDescription() {
                return ".txt file";
            }
        };
        fileChooser.setApproveButtonText("OK");
        fileChooser.setDialogTitle("Chọn file...");
        fileChooser.setFileFilter(ff);
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        int returnValue = fileChooser.showOpenDialog(null);
        if(returnValue == JFileChooser.APPROVE_OPTION)
        {
            File f = fileChooser.getSelectedFile();
            String s = f.getPath();
            realpath = s.replace("\\", "/");
        }
        
        
        String line;
        StringBuilder lines = new StringBuilder();
        FileReader reader;
        int numberOfUser;
        try 
        {
            reader = new FileReader(this.realpath);
            BufferedReader bufferedReader = new BufferedReader(reader);
            //Đọc dòng đầu tiên để biết số lượng User
            numberOfUser = Integer.parseInt(bufferedReader.readLine());
            listUser = new String[numberOfUser];
            int iLineIndex = 0;
            while((line = bufferedReader.readLine())!= null)
            {
                lines.append(line);
                lines.append("\n");
                if(iLineIndex == 0)
                {
                    continue;
                }
                else
                {
                    //Đọc các dòng tiếp theo để lấy danh sách User
                    listUser[iLineIndex]=line;
                }
                iLineIndex++;
            }
            this.jpwfMatKhau.setEnabled(true);
            this.jtfMSSV.setEnabled(true);
            this.jbtnDangNhap.setEnabled(true);
        }
        catch (IOException ex) 
        {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        /*int i=1;
        while(listUser[i] != null)
        {
            String[] user  = listUser[i].split("\\.");
            lines.append(user[0]);
        }*/
        //String[] user  = listUser[0].split("\\.");
        JOptionPane.showMessageDialog(null, listUser[0]);
    }//GEN-LAST:event_jbtnNapDuLieuMouseClicked

    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                Login loginGUI;
                loginGUI = new Login();
                loginGUI.show();
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JButton jbtnDangNhap;
    private javax.swing.JButton jbtnNapDuLieu;
    private javax.swing.JLabel jlblMSSV;
    private javax.swing.JPasswordField jpwfMatKhau;
    private javax.swing.JTextField jtfMSSV;
    // End of variables declaration//GEN-END:variables
    
}
